package com.example.controller;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.example.common.result.Result;
import com.example.entity.dto.KeepGetPageDto;
import com.example.entity.dto.KeepGetRecordDto;
import com.example.entity.matirx.KeepRecord;
import com.example.entity.vo.KeepGetVo;
import com.example.exception.BaseException;
import com.example.exception.SaveFailException;
import com.example.service.KeepGetRecordService;
import com.example.service.KeepRecordService;
import com.github.pagehelper.Page;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


@RestController
@DS("mes")
@Api(tags = "保养取样相关",position = 997)
@RequestMapping("/keepget")
public class KeepGetController {
    @Autowired
    private KeepGetRecordService keepGetRecordService;
    @Autowired
    private KeepRecordService keepRecordService;

    @ApiOperation("新建取样记录并同时生成保养记录")
    @PostMapping("/create")
    public Result creatRecord(@RequestBody KeepGetRecordDto record) {
        record.setGetTime(LocalDateTime.now());
        record.setStatus(2);
        boolean save = keepGetRecordService.save(record);
        if (!save) throw new SaveFailException("取样失败！");
        KeepRecord keepRecord = KeepRecord.builder().moudleId(record.getMoudleId()).planId(record.getPlanId())
                .status(1).getId(record.getId()).build();
        boolean save1 = keepRecordService.save(keepRecord);
        if (!save1) throw new SaveFailException("生成保养记录失败");
        return Result.success();
    }

    @ApiOperation("归还取样")
    @PostMapping("/returned")
    public Result updateRecord(@RequestBody KeepGetRecordDto record) {
        record.setStatus(1);
        record.setBackTime(LocalDateTime.now());
        keepGetRecordService.returned(record);
        keepRecordService.editStatus(record.getKeepRecordId());
        return Result.success();
    }

    @ApiOperation("删除取样记录")
    @DeleteMapping("/delete")
    public Result deleteGetRecord(@RequestBody List<Integer> ids) {
        boolean b = keepGetRecordService.removeByIds(ids);
        if (!b) throw new BaseException("删除取样记录失败！");
        return Result.success();
    }

    @ApiOperation("分页取样记录")
    @GetMapping("/page")
    public Result<Page<KeepGetVo>> pageGetRecord( KeepGetPageDto record) {
        Page<KeepGetVo> getVoPage = keepGetRecordService.pageVowithMoudleName(record);
        return Result.success(getVoPage);
    }
}
